package com.hdc.hdc.warehouseManage.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hdc.hdc.warehouseManage.entity.Outorder;
import com.hdc.hdc.warehouseManage.entity.vo.OrderVo;
import com.hdc.hdc.warehouseManage.repository.OutorderRepository;
import com.hdc.hdc.warehouseManage.service.OutorderServiceI;
import com.hdc.hdc.warehouseManage.utill.IsNotNullValit;

@Service
public class OutorderserviceImpl implements OutorderServiceI {
	
	@Autowired
	private OutorderRepository outorderRepository;
	
	@Resource
    private EntityManagerFactory sessionFactory;

	@Override
	public List<Outorder> queryOutorderDetailByVO(OrderVo vo) {
		
		List<Outorder> outorders = new ArrayList<Outorder>(10);
		
		EntityManager em = this.sessionFactory.createEntityManager();
		
		Map<String, String> params = new ConcurrentHashMap<String,String>(10);
		
		StringBuffer sb = new StringBuffer("from Outorder o left join OutorderAndGoods oag "
				+ " on o.outorderNum = oag.outordernum where 1=1 ");
		
		if(IsNotNullValit.StringIsNotNull(vo.getFromWhereHouse())) {
			sb.append(" o.fromWhereHouse = :fromWhereHouse");
			params.put("fromWhereHouse", vo.getFromWhereHouse());
		}
		
		if(IsNotNullValit.StringIsNotNull(vo.getFromWherePosition())) {
			sb.append(" o.fromWherePosition = :fromWherePosition");
			params.put("fromWherePosition", vo.getFromWherePosition());
		}
		
		if(IsNotNullValit.StringIsNotNull(vo.getOutorderNum())) {
			sb.append(" o.outorderNum = :outorderNum");
			params.put("outorderNum", vo.getOutorderNum());
		}
		
		if(IsNotNullValit.StringIsNotNull(vo.getGoodsName())) {
			sb.append(" oag.goodsName like :goodsName");
			params.put("goodsName", "%"+vo.getGoodsName()+"%");
		}
		
		if(IsNotNullValit.StringIsNotNull(vo.getSku())) {
			sb.append(" oag.goodsSku like :goodsSku");
			params.put("goodsSku", "%"+vo.getSku()+"%");
		}
		
		Query query = em.createQuery(sb.toString());
		
		Iterator<String> it = params.keySet().iterator();
		while(it.hasNext()) {
			String key = it.next();
			query.setParameter(key, params.get(key));
		}
		
		query.setFirstResult((vo.getPageNum()-1)*vo.getPageSize());
		query.setMaxResults(vo.getPageSize());
		
		return outorders;
	}

}
